package 代码随想录.链表.移除链表元素;

import java.util.List;

/**lc203. 移除链表元素
 * link：https://leetcode-cn.com/problems/remove-linked-list-elements/
 * @author ChenweiLin
 * @create 2021-12-01 22:18
 */
public class removeLinkedListElements {
    public static void main(String[] args) {
        ListNode a = new ListNode(7);
        ListNode b = new ListNode(7);
        ListNode c = new ListNode(7);
        ListNode d = new ListNode(7);
        ListNode e = new ListNode(7);
        ListNode f = new ListNode(7);
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = e;
        e.next = f;

        ListNode listNode = removeElements(a, 7);

        while (listNode.next != null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }

    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode removeElements(ListNode head, int val) {
        //特殊情况
        if(head == null){
            return null;
        }
        //伪头节点
        ListNode wei = new ListNode(-1,head);
        ListNode pre = wei;//cur节点的前一个节点，head的pre即是wei
        ListNode cur = head;//cur节点，从head开始
        //遍历整个列表
        while (cur != null){
            if (cur.val == val){//删除该节点
                pre.next = cur.next;//pre的next指向cur的next，这样cur即被删除
            }else {
                pre = cur;//不是要删除的节点，pre向后移动一位
            }
            //pre = cur;TODO:不能再if外面写pre向后移动，因为删除节点之后我们会马上检验新的cur,此时pre是没变的，因此有个if-else
            cur = cur.next;//cur向后移动

        }
        return wei.next;
    }





}


